package com.shanghaionstar.utils;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.onstar.cn.common.log.LogManager;

public class ListViewUtil {
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public static void setGridViewHeightBasedOnChildren(GridView gridView, int columnNum) {
        ListAdapter listAdapter = gridView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        int N = listAdapter.getCount();
//		int columnNum = gridView.getNumColumns();
        Context context = gridView.getContext();
        if (N > 0) {
            int verSpacing = gridView.getVerticalSpacing();
            View listItem = listAdapter.getView(0, null, gridView);
            listItem.measure(0, 0);
//			int itemHeight = (int) (85*context.getResources().getDisplayMetrics().density);
            int itemHeight = (int) (listItem.getMeasuredHeight() == 0 ? 80 * context.getResources().getDisplayMetrics().density : listItem.getMeasuredHeight());
            if (N % columnNum == 0) {
                totalHeight = itemHeight * (N / columnNum);
                totalHeight += verSpacing * (N / columnNum - 1);
            } else {
                totalHeight = itemHeight * (N / columnNum + 1);
                totalHeight += verSpacing * (N / columnNum);
            }

        }
        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        params.height = totalHeight;
        LogManager.getInstance().d("the house keeper grid view height is like =======>>" + totalHeight);
        gridView.setLayoutParams(params);
    }
}
